<template>
  <el-card class="box-card">
    <el-button @click="addTrademark" type="primary" size="default" icon="Plus">添加品牌</el-button>
    <el-table :data="trademarkArr" class="el-table" border>
      <el-table-column type="index" label="序号" width="60" align="center" />
      <el-table-column prop="tmName" label="名称" align="center" />
      <el-table-column prop="logoUrl" label="LOGO" align="center">
        <template #default="{ row, index }">
          <img class="trademark-logo" :src="row.logoUrl" alt="" />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center">
        <template #default="{ row, index }">
          <el-button @click="updateTrademark(row)" type="warning" size="small" icon="Edit" circle></el-button>
          <el-button @click="deleteTrademark(row)" type="danger" size="small" icon="Delete" circle></el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      @current-change="currentPageChange"
      @size-change="pageSizeChange"
      v-model:current-page="pageNo"
      v-model:page-size="limit"
      :page-sizes="[5, 10, 20, 50, 100, 200]"
      :background="true"
      layout="prev, pager, next, jumper, ->, sizes, total"
      :total="total"
    />
  </el-card>

  <el-dialog v-model="dialogFormVisible" :title="trademarkParams.id ? '更新品牌' : '添加品牌'">
    <el-form label-width="auto" :model="trademarkParams" :rules="rules" ref="formEle">
      <el-form-item label="品牌名称" prop="tmName">
        <el-input placeholder="请输入品牌名称" v-model="trademarkParams.tmName"></el-input>
      </el-form-item>
      <el-form-item label="LOGO" prop="logoUrl">
        <!-- 
          update组件属性：
              action:图片上传路径，需要带有'/api'
                  例如：'/api/admin/product/fileUpload'
        -->
        <el-upload
          v-model="trademarkParams.logoUrl"
          class="avatar-uploader"
          action="/api/admin/product/fileUpload"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
        >
          <img v-if="trademarkParams.logoUrl" :src="trademarkParams.logoUrl" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="cancelHandler">取消</el-button>
        <el-button type="primary" @click="confirmHandler">确认</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { Records, Trademark, TrademarkResponseData } from '@/api/product/trademark/types';
import { ElMessageBox, UploadProps } from 'element-plus';

//当前页码
const pageNo = ref<number>(1);
//当前页数据数
const limit = ref<number>(5);
//总数据条数
const total = ref<number>(0);
//商品列表
const trademarkArr = ref<Records>([]);
//是否显示添加修改对话框
const dialogFormVisible = ref<boolean>(false);
//新增品牌数据
const trademarkParams = reactive<Trademark>({
  tmName: '',
  logoUrl: '',
});
const formEle = ref();

const getHasTrademark = async (pager = 1) => {
  pageNo.value = pager;
  const result: TrademarkResponseData = await reqHasTrademark(pageNo.value, limit.value);
  if (result.code === 200) {
    total.value = result.data.total;
    limit.value = result.data.size;
    trademarkArr.value = result.data.records;
  }
};
onMounted(() => {
  getHasTrademark();
});
//当前页改变触发
const currentPageChange = () => {
  getHasTrademark(pageNo.value);
};
//页面数据项改变触发
const pageSizeChange = () => {
  getHasTrademark();
};

//添加
const addTrademark = () => {
  dialogFormVisible.value = true;
  //清空收集的数据
  trademarkParams.logoUrl = '';
  trademarkParams.tmName = '';
  trademarkParams.id = 0;
  //清空校验消息
  // formEle.value?.clearValidate(['tmName', 'logoUrl']);
  nextTick(() => {
    formEle.value.clearValidate(['tmName', 'logoUrl']);
  });
};
//更新
const updateTrademark = (row: Trademark) => {
  dialogFormVisible.value = true;
  //将两个对象合并
  Object.assign(trademarkParams, row);
  //清空校验消息
  nextTick(() => {
    formEle.value.clearValidate(['tmName', 'logoUrl']);
  });
};
//删除
const deleteTrademark = (row: Trademark) => {
  ElMessageBox.confirm(`确认要删除【${row.tmName}】这条数据吗？`, {
    title: '提示',
  })
    .then(async () => {
      const result = await reqDeleteTrademark(row.id as number);
      if (result.code === 200) {
        ElMessage.success('删除成功');
        getHasTrademark(trademarkArr.value.length > 1 ? pageNo.value : pageNo.value - 1);
      } else {
        ElMessage.error('删除失败');
      }
    })
    .catch(() => {
      ElMessage.success('已取消删除');
    });
};
//取消表单
const cancelHandler = () => {
  dialogFormVisible.value = false;
};
// 确认表单
const confirmHandler = async () => {
  // 提交之前验证表单项
  await formEle.value.validate();
  const result = await reqAddOrUpdateTrademark(trademarkParams);
  if (result.code === 200) {
    ElMessage.success(trademarkParams.id ? '更新品牌成功' : '添加品牌成功');
    getHasTrademark(trademarkParams.id ? pageNo.value : 1);
  } else {
    ElMessage.error(trademarkParams.id ? '更新品牌失败' : '添加品牌失败');
  }
  dialogFormVisible.value = false;
};
//文件上传成功时触发
const handleAvatarSuccess: UploadProps['onSuccess'] = (response) => {
  trademarkParams.logoUrl = response.data;
  //文件上传成功清理logo校验信息
  formEle.value.clearValidate('logoUrl');
};
//上传图片之前触发
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png' && rawFile.type !== 'image/gif') {
    ElMessage.error('头像图片格式必须是 JPG | PNG | GIF ！');
    return false;
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('头像图片大小不能超过2MB！');
    return false;
  }
  return true;
};
//自定义tmName校验规则
const validatorTmName = (rule: any, value: any, callBack: any) => {
  if (value === '') {
    callBack(new Error('品牌名称不能为空'));
  } else if (value.trim().length >= 2) {
    callBack();
  } else {
    callBack(new Error('品牌名称长度大于等于两位'));
  }
};
//自定义logoUrl校验规则
const validatorLogoUrl = (rule: any, value: any, callBack: any) => {
  if (value) {
    callBack();
  } else {
    callBack(new Error('品牌Logo必须上传'));
  }
};
//校验规则
const rules = {
  tmName: [
    {
      required: true,
      trigger: 'blur',
      validator: validatorTmName,
    },
  ],
  logoUrl: [
    {
      required: true,
      validator: validatorLogoUrl,
    },
  ],
};
</script>

<style lang="scss" scoped>
.box-card {
  .el-table {
    width: 100%;
    margin: 10px 0;
    height: calc(100vh - $base-tabbar-height - 148px);

    .trademark-logo {
      width: 40px;
      height: 40px;
    }
  }
}
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
